#include "map_normal.h"

#include "edge_sobel.h"
#include "map_height.h"

MapNormal::MapNormal(PNM* img) :
    Convolution(img)
{
}

MapNormal::MapNormal(PNM* img, ImageViewer* iv) :
    Convolution(img, iv)
{
}

PNM* MapNormal::transform()
{
    int width  = image->width(),
        height = image->height();

    double strength = getParameter("strength").toDouble();

    PNM* newImage = new PNM(width, height, image->format());

	auto mheight = new MapHeight(image);
	auto height_map = mheight->transform();

	auto esobel = new EdgeSobel(height_map);
	auto g_x = esobel->rawHorizontalDetection();
	auto g_y = esobel->rawVerticalDetection();

	for (int i = 0; i < width; i++)
	{
		for (int j = 0; j < height; j++)
		{
			auto dx = ((*g_x)(i, j))/255.0f;
			auto dy = ((*g_y)(i, j))/255.0f;
			auto dz = 1.0f / strength;

			auto lenght = sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2));
			dx /= lenght;
			dy /= lenght;
			dz /= lenght;

			dx = (dx + 1.0f)*(255.0f/strength);
			dy = (dy + 1.0f)*(255.0f/strength);
			dz = (dz + 1.0f)*(255.0f/strength);

			auto c = QColor(dx, dy, dz);
			newImage->setPixel(i, j, c.rgb());

		}
	}

    return newImage;
}
